<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-left">
        <div class="brand">
          <div class="logo">EDU</div>
          <h1>教育共享平台</h1>
          <p class="slogan">让知识触手可及</p>
        </div>
        <div class="decoration">
          <div class="vase-image">
            <img v-if="avatarUrl" :src="avatarUrl" alt="用户头像" class="user-avatar-preview">
            <div v-else class="default-avatar-preview">
              <svg xmlns="http://www.w3.org/2000/svg" width="80" height="80" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">
                <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path>
                <circle cx="12" cy="7" r="4"></circle>
              </svg>
            </div>
          </div>
          <div class="stats-card">
            <div class="stat-item">
              <h3>5.8</h3>
            </div>
            <div class="stat-item">
              <h3>99+</h3>
            </div>
            <div class="stat-item">
              <h3>110K</h3>
            </div>
          </div>
        </div>
      </div>
      <div class="login-right">
        <div class="login-header">
          <h2>欢迎登录</h2>
          <p>请使用您的账号密码登录系统</p>
        </div>
        <form class="login-form" @submit.prevent="handleSubmit">
          <div class="form-group">
            <div class="input-group">
              <div class="input-icon">
                <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                  <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path>
                  <circle cx="12" cy="7" r="4"></circle>
                </svg>
              </div>
              <input 
                type="text" 
                id="username" 
                v-model="formData.userName" 
                placeholder="请输入用户名"
                required
                @input="handleUserNameInput"
              >
            </div>
          </div>
          <div class="form-group">
            <div class="input-group">
              <div class="input-icon">
                <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                  <rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect>
                  <path d="M7 11V7a5 5 0 0 1 10 0v4"></path>
                </svg>
              </div>
              <input 
                type="password" 
                id="password" 
                v-model="formData.password" 
                placeholder="请输入密码"
                required
              >
            </div>
          </div>
          <div class="form-group">
            <div class="input-group">
              <div class="input-icon">
                <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                  <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm-1-13h2v6h-2zm0 8h2v2h-2z"/>
                </svg>
              </div>
              <input 
                type="text" 
                v-model="formData.captcha" 
                placeholder="请输入验证码"
                required
              >
              <div class="captcha-container" @click="refreshCaptcha">
                <img 
                  :src="captchaUrl" 
                  alt="验证码" 
                  class="captcha-img"
                  @error="handleImageError"
                >
                <div class="refresh-icon">
                  <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                    <path d="M21.5 2v6h-6M2.5 22v-6h6M2 11.5a10 10 0 0 1 18.8-4.3M22 12.5a10 10 0 0 1-18.8 4.3"/>
                  </svg>
                </div>
              </div>
            </div>
          </div>
          <div class="form-options">
            <div class="remember-me-container">
              <input 
                type="checkbox" 
                id="remember"
                v-model="rememberMe"
              >
              <label for="remember">记住我</label>
            </div>
            <router-link to="/forgot-password" class="forgot-link">忘记密码？</router-link>
          </div>
          <div class="form-group">
            <button type="submit" :disabled="loading" class="submit-btn">
              <span class="btn-text">{{ loading ? '登录中...' : '登录' }}</span>
            </button>
          </div>
          <div class="bottom-links">
            <div class="auth-links">
              <span class="register-text">还没有账号？</span>
              <router-link to="/register" class="auth-link">立即注册</router-link>
              <span class="divider">|</span>
              <el-button link @click="$router.push('/phone-login')" class="auth-link">手机号登录</el-button>
            </div>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script>
/**
 * 登录页面组件
 * 提供用户登录功能，包括：
 * - 用户名和密码验证
 * - 验证码验证
 * - 记住我功能
 * - 响应式布局支持
 */
import { login, generateCaptchaUrl, generateCaptchaId, verifyCaptcha, getUserAvatarByName } from '@/api/user'
import { TokenManager } from '@/utils/request'
import { useRouter } from 'vue-router'
import { onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'

export default {
  name: 'LoginView',
  
  /**
   * 组件数据
   * @returns {Object} 组件数据对象
   */
  setup() {
    const router = useRouter()
    const formData = reactive({
      userName: '',   // 用户名
      password: '',   // 密码
      captcha: ''     // 验证码
    })
    const rememberMe = ref(false)
    const loading = ref(false)
    const captchaUrl = ref('')
    const captchaId = ref('')
    const avatarUrl = ref('')
    const avatarTimer = ref(null)  // 用于防抖的定时器

    // 获取用户头像的函数
    const fetchUserAvatar = async (username) => {
      try {
        const avatar = await getUserAvatarByName(username)
        avatarUrl.value = avatar
      } catch (error) {
        // 获取头像失败时，使用默认头像
        avatarUrl.value = ''
      }
    }

    // 处理用户名输入，获取头像
    const handleUserNameInput = () => {
      // 清除之前的定时器
      if (avatarTimer.value) {
        clearTimeout(avatarTimer.value)
      }
      
      const username = formData.userName.trim()
      if (username) {
        // 设置新的定时器，500ms 后执行
        avatarTimer.value = setTimeout(() => {
          fetchUserAvatar(username)
        }, 500)
      } else {
        avatarUrl.value = ''
      }
    }

    // 在组件创建时
    onMounted(() => {
      refreshCaptcha()
      // 从本地存储加载保存的用户名和密码
      const savedUser = JSON.parse(localStorage.getItem('rememberedUser'))
      if (savedUser) {
        formData.userName = savedUser.userName
        formData.password = savedUser.password
        rememberMe.value = true
        // 立即获取头像
        if (savedUser.userName) {
          fetchUserAvatar(savedUser.userName)
        }
      }
    })

    /**
     * 刷新验证码
     */
    const refreshCaptcha = () => {
      try {
        // 使用API函数生成验证码ID
        const id = generateCaptchaId()
        // 使用API函数生成验证码URL
        captchaUrl.value = generateCaptchaUrl(id)
        captchaId.value = id
      } catch (error) {
        // 验证码生成失败，显示错误提示
        ElMessage.error('验证码生成失败，请刷新页面重试')
      }
    }

    /**
     * 处理验证码图片加载错误
     * 显示错误提示并刷新验证码
     */
    const handleImageError = () => {
      ElMessage.error('验证码加载失败，请点击刷新')
      refreshCaptcha()
    }

    /**
     * 处理表单提交
     */
    const handleSubmit = async () => {
      try {
        loading.value = true
        
        // 验证验证码
        const captchaValid = await verifyCaptcha({
          captchaId: captchaId.value,
          captcha: formData.captcha
        })
        if (!captchaValid) {
          ElMessage.error('验证码错误')
          refreshCaptcha()
          return
        }
        
        // 调用登录接口
        const response = await login(formData)
        console.log('登录响应:', response)
        
        // 检查响应数据结构
        if (!response || typeof response !== 'object') {
          throw new Error('登录响应格式错误')
        }
        
        // 确保token存在
        if (!response.data) {
          throw new Error('登录失败：未获取到token')
        }
        
        // 获取用户角色，如果不存在则默认为空字符串
        const userRole = response.role || ''
        
        // 保存token和用户角色
        if (rememberMe.value) {
          // 如果选择记住我，同时保存在localStorage和sessionStorage中
          localStorage.setItem('token', response.data)
          localStorage.setItem('userRole', userRole)
          sessionStorage.setItem('token', response.data)
          sessionStorage.setItem('userRole', userRole)
        } else {
          // 如果不记住，只保存在sessionStorage中，并清除localStorage
          sessionStorage.setItem('token', response.data)
          sessionStorage.setItem('userRole', userRole)
          localStorage.removeItem('token')
          localStorage.removeItem('userRole')
        }
        
        // 设置token到请求头
        TokenManager.setToken(response.data)
        
        ElMessage.success('登录成功')
        
        // 检查用户角色并跳转
        const normalizedRole = String(userRole).toUpperCase()
        if (normalizedRole === 'ROOT') {
          router.push('/admin')
        } else {
          router.push('/')
        }
      } catch (error) {
        console.error('登录失败:', error)
        ElMessage.error(error.message || '登录失败，请重试')
        refreshCaptcha()
      } finally {
        loading.value = false
      }
    }

    return {
      formData,
      rememberMe,
      loading,
      captchaUrl,
      captchaId,
      avatarUrl,
      avatarTimer,
      handleUserNameInput,
      handleSubmit,
      refreshCaptcha,
      handleImageError
    }
  }
}
</script>

<style scoped>
/* 添加全局背景样式 */
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: #fff;
  padding: 20px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  position: fixed;  /* 固定定位 */
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  overflow-y: auto;  /* 允许内容滚动 */
}


.login-box {
  display: flex;
  background: #fff;
  border-radius: 24px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.05);
  width: 1200px;
  min-height: 700px;
  overflow: hidden;
}

.login-left {
  flex: 1.2;
  background: #e9ecef;
  padding: 60px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  position: relative;
}

.decoration {
  position: relative;
  height: 400px;
  margin-top: 40px;
}

.vase-image {
  width: 200px;
  height: 200px;
  position: absolute;
  left: 40px;
  bottom: 100px;
  border-radius: 50%;
  overflow: hidden;
  background: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.user-avatar-preview {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.default-avatar-preview {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
}

.default-avatar-preview svg {
  width: 80px;
  height: 80px;
  color: #c0c4cc;
}

.vase-image:hover {
  transform: translateY(-5px);
  box-shadow: 0 12px 32px rgba(0, 0, 0, 0.15);
}

.stats-card {
  position: absolute;
  right: 20px;
  bottom: 40px;
  background: white;
  padding: 30px;
  border-radius: 24px;
  display: flex;
  gap: 40px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
}

.stat-item h3 {
  color: #343a40;
  font-size: 1.5rem;
  font-weight: 600;
}

.login-right {
  flex: 1;
  padding: 60px 80px;
  background: white;
}

.login-header {
  margin-bottom: 3rem;
}

.login-header h2 {
  color: #1f2937;
  font-size: 2.5rem;
  margin-bottom: 1rem;
  font-weight: 600;
}

.login-header p {
  color: #6b7280;
  font-size: 1.1rem;
}

.form-group {
  margin-bottom: 1.5rem;
}

.form-group label {
  display: none;
}

.input-group {
  position: relative;
  display: flex;
  align-items: center;
  border: 2px solid #e5e7eb;
  border-radius: 12px;
  transition: all 0.3s ease;
  overflow: hidden;
}

.input-group:focus-within {
  border-color: #1890ff;
  box-shadow: 0 0 0 3px rgba(24, 144, 255, 0.1);
}

.input-icon {
  padding: 0 1rem;
  color: #9ca3af;
}

input {
  width: 100%;
  padding: 0.75rem;
  background: transparent;
  border: none;
  font-size: 1rem;
  color: #1f2937;
  outline: none;
}

input::placeholder {
  color: #9ca3af;
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 3rem;
}

.remember-me-container {
  display: flex;
  align-items: center;
  gap: 8px;
}

.remember-me-container input[type="checkbox"] {
  width: 16px;
  height: 16px;
  margin: 0;
  cursor: pointer;
}

.remember-me-container label {
  color: #4b5563;
  cursor: pointer;
  user-select: none;
}

.forgot-link {
  color: #1890ff;
  text-decoration: none;
  font-weight: 500;
  transition: color 0.3s;
}

.forgot-link:hover {
  color: #096dd9;
}

.submit-btn {
  width: 100%;
  padding: 1rem;
  background: #343a40;
  color: white;
  border: none;
  border-radius: 12px;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.submit-btn:hover:not(:disabled) {
  background: #212529;
}

.submit-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

.bottom-links {
  margin-top: 2rem;
  text-align: center;
}

.auth-links {
  display: inline-flex;
  align-items: center;
  gap: 6px;
}

.register-text {
  color: #6b7280;
  font-size: 14px;
}

.divider {
  color: #e5e7eb;
}

.auth-link {
  color: #1890ff;
  font-weight: 500;
  text-decoration: none;
  font-size: 14px;
  padding: 0;
  height: auto;
}

.auth-link:hover {
  text-decoration: underline;
  color: #40a9ff;
}

:deep(.auth-link.el-button) {
  color: #1890ff !important;
}

:deep(.auth-link.el-button:hover) {
  color: #40a9ff !important;
}

@media (max-width: 1024px) {
  .login-box {
    width: 800px;
  }
  
  .login-right {
    padding: 40px;
  }
}

@media (max-width: 768px) {
  .login-left {
    display: none;
  }
  
  .login-box {
    width: 100%;
    max-width: 500px;
  }
}

.captcha-container {
  position: relative;
  min-width: 130px;
  height: 38px;
  border-left: 2px solid #e5e7eb;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 15px;
  margin-left: auto;
  margin-right: 10px;
}

.captcha-img {
  height: 32px;
  width: auto;
  max-width: none;
  object-fit: contain;
  border-radius: 4px;
  transform: translateX(-5px);
}

.refresh-icon {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: rgba(255, 255, 255, 0.8);
  border-radius: 50%;
  padding: 4px;
  display: none;
  color: #1890ff;
}

.captcha-container:hover .refresh-icon {
  display: block;
}

.captcha-container:hover .captcha-img {
  opacity: 0.7;
}

.input-group input {
  flex: 1;
  min-width: 0;
  padding: 0.75rem 1rem;
}

/* 添加验证码输入框组的特殊样式 */
.code-group {
  display: flex;
  align-items: stretch;
  padding-right: 0;
}

.code-group input {
  flex: 1;
  border-right: none;
  padding-right: 0.5rem;
  max-width: calc(100% - 130px);
}

.avatar-container {
  display: flex;
  justify-content: center;
  margin-bottom: 24px;
}

.user-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border: 2px solid #fff;
  transition: all 0.3s ease;
}

.default-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background-color: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  font-size: 40px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border: 2px solid #fff;
}

.user-avatar:hover {
  transform: scale(1.05);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15);
}

.form-group {
  margin-top: 24px;
}

.input-group {
  margin-bottom: 20px;
}
</style> 